package com.lt.bigevent.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lt.bigevent.entity.Article;
import com.lt.bigevent.service.ArticleService;
import com.lt.bigevent.util.ThreadLocalUtil;
import com.lt.bigevent.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.Map;


@RestController
@RequestMapping("/article")
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    @PostMapping("/add")
    public Result<String> add(@RequestBody @Validated Article article) {
        //补充属性值
        article.setCreateTime(new Date());
        article.setUpdateTime(new Date());

        Map<String,Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("userId");
        article.setCreateUser(userId);
        articleService.save(article);
        return Result.success();
    }

    @GetMapping("/list")
    public Result<IPage<Article>> list(
            @RequestParam(value = "pageNum",required = true) Integer pageNum,
            @RequestParam(value = "pageSize",required = true) Integer pageSize,
            @RequestParam(required = false) Integer categoryId,
            @RequestParam(required = false) String state){
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("userId");
        LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<>();
        if(categoryId != null){
            wrapper.eq(Article::getCategoryId,categoryId);
        }
        if(state != null){
           wrapper.eq(Article::getState,state);
        }
        wrapper.eq(Article::getCreateUser,userId);
        Page<Article> page = new Page<Article>(pageNum, pageSize);
        IPage<Article> pageList = articleService.page(page, wrapper);
        return Result.success(pageList);
    }
}
